package com.ruoyi.web.controller.module.attendance;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.attendance.AttendanceGroup;
import com.ruoyi.system.domain.module.attendance.AttendanceGroupUser;
import com.ruoyi.system.domain.module.attendance.AttendanceWorkShift;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.service.module.attendance.IAttendanceGroupService;
import com.ruoyi.system.service.module.attendance.IAttendanceGroupUserService;
import com.ruoyi.system.service.module.attendance.IAttendanceWorkShiftService;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.property.IPropertyUserService;
import com.ruoyi.system.service.system.ISysUserService;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 考勤组Controller
 *
 * @author ruoyi
 * @date 2022-09-20
 */
@Validated
@Api(value = "考勤组控制器", tags = {"考勤组管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/attendance/group")
public class AttendanceGroupController extends BaseController {

    private final IAttendanceGroupService attendanceGroupService;
    private final IEstateService estateService;
    private final IPropertyService propertyService;
    private final ISysUserService sysUserService;
    private final IAttendanceWorkShiftService workShiftService;
    private final IPropertyUserService propertyUserService;
    private final IAttendanceGroupUserService attendanceGroupUserService;
    /**
     * 查询考勤组列表
     */
    @ApiOperation("查询考勤组列表")
    @PreAuthorize("@ss.hasPermi('module:attendanceGroup:list')")
    @GetMapping("/list")
    public TableDataInfo<AttendanceGroup> list(@Validated AttendanceGroup attendanceGroup) {
        SysUser sysUser = sysUserService.selectUserByUserName(attendanceGroup.getSysUserName());
            QueryWrapper<AttendanceGroup> qw = new QueryWrapper<>();
            if(attendanceGroup.getPropertyId()!=null){
                qw.eq("property_id",attendanceGroup.getPropertyId());
            }
            if(attendanceGroup.getEstateId()!=null){
                qw.eq("estate_id",attendanceGroup.getEstateId());
            }
            TableDataInfo<AttendanceGroup> td = PageUtils.buildDataInfo(attendanceGroupService.page(PageUtils.buildPage(),qw));
            List<AttendanceGroup> list = td.getRows();
            for(AttendanceGroup list1:list){
                Integer w1 = list1.getWorkDay1();
                Integer w2 = list1.getWorkDay2();
                Integer w3 = list1.getWorkDay3();
                Integer w4 = list1.getWorkDay4();
                Integer w5 = list1.getWorkDay5();
                Integer w6 = list1.getWorkDay6();
                Integer w7 = list1.getWorkDay7();
                if(w1==1&&w2==1&&w3==1&&w4==1&&w5==1){
                    if(w6==1 && w7==1){
                        list1.setWorkSystem(0);
                    }else if((w6==1 && w7==0)||(w6==0 && w7==1)){
                        list1.setWorkSystem(1);
                    }else if(w6==0 && w7==0){
                        list1.setWorkSystem(2);
                    }
                }else {
                    list1.setWorkSystem(3);
                }
                if (list1.getEstateId()!=null){
                    Estate estate=estateService.findById(list1.getEstateId());
                    list1.setEstateName(estate.getEstateName());
                }else {
                    list1.setEstateName("未绑定");
                }
                Property property=propertyService.findById(list1.getPropertyId());

                list1.setPropertyName(property.getPropertyName());
                if (list1.getWorkShift()!=null){
                    AttendanceWorkShift attendanceWorkShift =workShiftService.findById(list1.getWorkShift());
                    list1.setShiftName(attendanceWorkShift.getShiftName());
                }else {
                    list1.setShiftName("未设置");
                }
            }
            return td;
    }

    /**
     * 导出考勤组列表
     */
    @ApiOperation("导出考勤组列表")
    @PreAuthorize("@ss.hasPermi('module:attendanceGroup:export')")
    @Log(title = "考勤组", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<AttendanceGroup> export(@Validated AttendanceGroup attendanceGroup) {
        List<AttendanceGroup> list = attendanceGroupService.list();
        ExcelUtil<AttendanceGroup> util = new ExcelUtil<AttendanceGroup>(AttendanceGroup.class);
        return util.exportExcel(list, "考勤组");
    }

    /**
     * 获取考勤组详细信息
     */
    @ApiOperation("获取考勤组详细信息")
    @PreAuthorize("@ss.hasPermi('module:attendanceGroup:query')")
    @GetMapping("/{id}")
    public AjaxResult<AttendanceGroup> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        AttendanceGroup attendanceGroup = attendanceGroupService.getById(id);
        QueryWrapper<AttendanceGroupUser> qw1=new QueryWrapper<>();
        qw1.eq("group_id",attendanceGroup.getId());
        List<AttendanceGroupUser> list=attendanceGroupUserService.list(qw1);
        if (list!=null){
            ArrayList<Integer> user=new ArrayList<>();
            for (AttendanceGroupUser list1:list){
                user.add(Math.toIntExact(list1.getSysUserId()));
            }
            List<Integer> arrString = user;
            attendanceGroup.setUserIds(arrString);
        }
        return AjaxResult.success(attendanceGroup);
    }

    /**
     * 新增考勤组
     */
    @ApiOperation("新增考勤组")
    @PreAuthorize("@ss.hasPermi('module:attendanceGroup:add')")
    @Log(title = "考勤组", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody AttendanceGroup attendanceGroup) {
        if (attendanceGroup.getGroupName()!=null){
            AttendanceGroup group = attendanceGroupService.selectByUniqueColumn("group_name",attendanceGroup.getGroupName());
            if (group!=null){
                return AjaxResult.error("新建考勤组'" + attendanceGroup.getGroupName() + "'失败，组名已存在");
            }
        }
        if(attendanceGroup.getWorkSystem()!=null){
            if(attendanceGroup.getWorkSystem()!=3){
                attendanceGroup.setWorkDay1(1);
                attendanceGroup.setWorkDay2(1);
                attendanceGroup.setWorkDay3(1);
                attendanceGroup.setWorkDay4(1);
                attendanceGroup.setWorkDay5(1);
                if(attendanceGroup.getWorkSystem()==0){
                    attendanceGroup.setWorkDay6(1);
                    attendanceGroup.setWorkDay7(1);
                }else if(attendanceGroup.getWorkSystem()==2){
                    attendanceGroup.setWorkDay6(0);
                    attendanceGroup.setWorkDay7(0);
                }else {
                    if(attendanceGroup.getRest()==0){
                        attendanceGroup.setWorkDay6(1);
                        attendanceGroup.setWorkDay7(0);
                    }else if(attendanceGroup.getRest()==1){
                        attendanceGroup.setWorkDay6(0);
                        attendanceGroup.setWorkDay7(1);
                    }
                }
            }
        }
        Property property=propertyService.findById(attendanceGroup.getPropertyId());
        attendanceGroup.setPropertyName(property.getPropertyName());
        if (attendanceGroup.getEstateId()!=null){
            Estate estate=estateService.findById(attendanceGroup.getEstateId());
            attendanceGroup.setEstateName(estate.getEstateName());
        }else {
            attendanceGroup.setEstateName("未绑定小区");
        }
        boolean pd=attendanceGroupService.save(attendanceGroup);
        if (pd=false){
            return AjaxResult.error("新建考勤组'" + attendanceGroup.getGroupName() + "'失败");
        }
        if (attendanceGroup.getUserIds()!=null){
//            String[] id = attendanceGroup.getUserIds().split(",");
            for (Integer userId:attendanceGroup.getUserIds()){
               SysUser user=sysUserService.selectUserById(Long.valueOf(userId));
               AttendanceGroupUser groupUser=new AttendanceGroupUser();
               if (user!=null){
                    groupUser.setGroupName(attendanceGroup.getGroupName());
                    groupUser.setPropertyId(attendanceGroup.getPropertyId());
                    groupUser.setPropertyName(attendanceGroup.getPropertyName());
                    if (attendanceGroup.getEstateId()!=null){
                        groupUser.setEstateId(attendanceGroup.getEstateId());
                        groupUser.setEstateName(attendanceGroup.getEstateName());
                    }else {
                        groupUser.setEstateName("未绑定小区");
                    }
                    groupUser.setUserId(0);
                    groupUser.setUserType(1);
                    groupUser.setSysUserId(user.getUserId());
                    groupUser.setState(1);
                    groupUser.setIsCheckHoliday(0);
                    QueryWrapper<AttendanceGroupUser> qw =new QueryWrapper<>();
                    qw.eq("sys_user_id",user.getUserId());
                    List<AttendanceGroupUser> user2=attendanceGroupUserService.list(qw);
                    if (user2!=null){
                        groupUser.setIsDefault(0);
                    }else {
                        groupUser.setIsDefault(1);
                    }
                    AttendanceGroup group1 = attendanceGroupService.selectByUniqueColumn("group_name",attendanceGroup.getGroupName());
                    groupUser.setGroupId(group1.getId());
                    if (attendanceGroup.getIsDefault()!=null){
                        groupUser.setIsDefault(attendanceGroup.getIsDefault());
                    }
                    boolean pd2=attendanceGroupUserService.save(groupUser);
                    if (pd2=false){
                        return AjaxResult.error("用户'" + groupUser.getSysUserId() + "'添加失败");
                    }
               }
            }
        }
        return toAjax(1);
    }

    /**
     * 修改考勤组
     */
    @ApiOperation("修改考勤组")
    @PreAuthorize("@ss.hasPermi('module:attendanceGroup:edit')")
    @Log(title = "考勤组", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody AttendanceGroup attendanceGroup) {
        if(attendanceGroup.getWorkSystem()!=null){
            if(attendanceGroup.getWorkSystem()!=3){
                attendanceGroup.setWorkDay1(1);
                attendanceGroup.setWorkDay2(1);
                attendanceGroup.setWorkDay3(1);
                attendanceGroup.setWorkDay4(1);
                attendanceGroup.setWorkDay5(1);
                if(attendanceGroup.getWorkSystem()==0){
                    attendanceGroup.setWorkDay6(1);
                    attendanceGroup.setWorkDay7(1);
                }else if(attendanceGroup.getWorkSystem()==2){
                    attendanceGroup.setWorkDay6(0);
                    attendanceGroup.setWorkDay7(0);
                }else {
                    if(attendanceGroup.getRest()==0){
                        attendanceGroup.setWorkDay6(1);
                        attendanceGroup.setWorkDay7(0);
                    }else if(attendanceGroup.getRest()==1){
                        attendanceGroup.setWorkDay6(0);
                        attendanceGroup.setWorkDay7(1);
                    }
                }
            }
        }
        Property property=propertyService.findById(attendanceGroup.getPropertyId());
        attendanceGroup.setPropertyName(property.getPropertyName());
        if (attendanceGroup.getEstateId()!=null){
            Estate estate=estateService.findById(attendanceGroup.getEstateId());
            attendanceGroup.setEstateName(estate.getEstateName());
        }

        if (attendanceGroup.getUserIds()!=null){
            QueryWrapper<AttendanceGroupUser> qw1=new QueryWrapper<>();
            qw1.eq("group_id",attendanceGroup.getId());
            List<AttendanceGroupUser> list=attendanceGroupUserService.list(qw1);
            List<Integer> newList = new ArrayList<>();
            List<Integer> oldList = new ArrayList<>();
            for (Integer userId:attendanceGroup.getUserIds()){
                newList.add(Integer.valueOf(userId));
            }
            for (AttendanceGroupUser list1:list){
                oldList.add(Math.toIntExact(list1.getSysUserId()));
            }
            List<Integer> delList = new ArrayList<>(CollectionUtils.subtract(oldList, newList));
            List<Integer> addList = new ArrayList<>(CollectionUtils.subtract(newList, oldList));

            System.out.println("删除"+delList);
            System.out.println("添加"+addList);
            for (Integer list1:delList){
                QueryWrapper<AttendanceGroupUser> qw=new QueryWrapper<>();
                qw.eq("sys_user_id",list1);
                attendanceGroupUserService.remove(qw);
            }
            for (Integer userId:addList){
                SysUser user=sysUserService.selectUserById(Long.valueOf(userId));
                AttendanceGroupUser groupUser=new AttendanceGroupUser();
                if (user!=null){
                    groupUser.setGroupName(attendanceGroup.getGroupName());
                    groupUser.setPropertyId(attendanceGroup.getPropertyId());
                    groupUser.setPropertyName(attendanceGroup.getPropertyName());
                    if (attendanceGroup.getEstateId()!=null){
                        groupUser.setEstateId(attendanceGroup.getEstateId());
                        groupUser.setEstateName(attendanceGroup.getEstateName());
                    }else {
                        groupUser.setEstateName("未绑定小区");
                    }
                    groupUser.setUserId(0);
                    groupUser.setUserType(1);
                    groupUser.setSysUserId(user.getUserId());
                    groupUser.setState(1);
                    groupUser.setIsCheckHoliday(0);
                    QueryWrapper<AttendanceGroupUser> qw =new QueryWrapper<>();
                    qw.eq("sys_user_id",user.getUserId());
                    List<AttendanceGroupUser> user2=attendanceGroupUserService.list(qw);
                    if (user2!=null){
                        groupUser.setIsDefault(0);
                    }else {
                        groupUser.setIsDefault(1);
                    }
                    AttendanceGroup group1 = attendanceGroupService.selectByUniqueColumn("group_name",attendanceGroup.getGroupName());
                    groupUser.setGroupId(group1.getId());
                    if (attendanceGroup.getIsDefault()!=null){
                        groupUser.setIsDefault(attendanceGroup.getIsDefault());
                    }
                    boolean pd2=attendanceGroupUserService.save(groupUser);
                    if (pd2=false){
                        return AjaxResult.error("用户'" + groupUser.getSysUserId() + "'添加失败");
                    }
                }
            }
        }
        return toAjax(attendanceGroupService.updateById(attendanceGroup) ? 1 : 0);
    }

    /**
     * 删除考勤组
     */
    @ApiOperation("删除考勤组")
    @PreAuthorize("@ss.hasPermi('module:attendanceGroup:remove')")
    @Log(title = "考勤组" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(attendanceGroupService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
